<template>
  <section class="todoapp">
    <!-- 使用组件 -->
    <todo-header :list="list" @addTask="addTaskHandler"></todo-header>
    <todo-main @delTask="delTaskHandler" :list="showList"></todo-main>
    <todo-footer
      @clearDone="clearDoneHandler"
      @changeTask="changeTaskHeadler"
      :list="showList"
    ></todo-footer>
  </section>
</template>

<script>
// 引入子组件
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter.vue";

export default {
  // 注册组件
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem("list") || "[]"),
      isSel: "all",
    };
  },
  methods: {
    addTaskHandler(taskName) {
      let id =
        this.list.length > 0 ? this.list[this.list.length - 1].id + 1 : 100;
      this.list.push({
        id,
        name: taskName,
        isDone: false,
      });
    },
    delTaskHandler(id) {
      // console.log(id);
      let index = this.list.findIndex((item) => (item.id = id));
      this.list.splice(index, 1);
    },
    changeTaskHeadler(isSel) {
      // console.log(isSel);
      this.isSel = isSel;
    },
    clearDoneHandler() {
      let arr = this.list.filter((item) => !item.isDone);
      this.list = arr;
    },
  },
  computed: {
    showList() {
      // console.log(this.isSel);
      // 根据isSel的值来决定筛选的数据返回
      if (this.isSel === "no") {
        return this.list.filter((item) => !item.isDone);
      } else if (this.isSel === "yes") {
        return this.list.filter((item) => item.isDone);
      } else {
        return this.list;
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        return localStorage.setItem("list", JSON.stringify(this.list));
      },
    },
  },
};
</script>

<style>
</style>
